//
//  InputPayViewController.m
//  BaseProject
//
//  Created by 王盼盼 on 2024/9/6.
//  Copyright © 2024 wangpanpan. All rights reserved.
//

#import "InputPayViewController.h"
#import "InputPayItemModel.h"
#import "InputPayItemView.h"
#import "UMSPPPayUnifyPayPlugin.h"
#import "InputPayJsonModel.h"
#import "LKLWebViewController.h"
#import "InputLKLResultModel.h"
#import "YunOrderListModel.h"
@interface InputPayViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) NSMutableArray<InputPayItemModel *> *dataList;
@property(nonatomic, strong) NSMutableArray<InputPayItemView *> *views;
@property(nonatomic, strong) UIView *bgView;
@property(nonatomic, strong) UIButton *payButton;
@property(nonatomic, strong) InputPayItemView *preItemView;
@property(nonatomic, strong) UITextField *textField;
@property(nonatomic, strong) InputPayJsonModel *dataModel;
@end

@implementation InputPayViewController
- (void)dealloc {
    NSLog(@"InputPayViewController ---dealloc");
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"支付";
    [self preData];
    [self makeUI];
    [self handleEvent];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.payButton.bottom = self.view.height - (kBottomSafeHeight + 26);
}
- (void)makeUI {
    [self.view addSubview:self.textField];
    [self.view addSubview:self.bgView];
    [self.view addSubview:self.payButton];
    [self updateListView];
    
    self.bgView.top = self.textField.bottom + 20;
}
- (void)preData {
    if (self.dataJson != nil) {
        self.dataModel = [InputPayJsonModel modelWithJSON:self.dataJson];
    } else if (self.orderModel != nil) {
        InputPayJsonModel *tempModel = [[InputPayJsonModel alloc]init];
        tempModel.sellerId = self.orderModel.sellerId;
        tempModel.type = self.orderModel.type;
        tempModel.orderId = self.orderModel.orderId;
        self.dataModel = tempModel;
    }
    
    for (NSInteger index = 0; index < 3; index ++) {
        InputPayItemModel *itemModel = [[InputPayItemModel alloc]init];
        if (index == 0) {
            itemModel.title = @"支付宝支付";
            itemModel.localImagePath = @"pay_zhifubao";
            itemModel.Id = @"ALIPAY";
            itemModel.channel = CHANNEL_ALIPAY;
            itemModel.subTitle = @"优惠折扣立减";
        } else if (index == 1) {
            itemModel.title = @"微信支付";
            itemModel.localImagePath = @"pay_weixin";
            itemModel.Id = @"WECHAT";
            itemModel.channel = CHANNEL_WEIXIN;
            itemModel.subTitle = @"优惠折扣立减";
        } else if (index == 2) {
            if (self.dataModel.isJiuDian) {
                continue;
            }
            itemModel.title = @"云闪付";
            itemModel.localImagePath = @"pay_yun";
            //itemModel.Id = @"YUNPAY";
            itemModel.Id = @"UNION";
            //itemModel.channel = ;
            itemModel.subTitle = @"分期免惠免手续费";
        }
        [self.dataList addObject:itemModel];
        
        if (index == 0) {
            itemModel.isSelect = YES;
        }
    }
}
- (void)handleEvent {
    [self.payButton addTarget:self action:@selector(clickPayButton:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)updateListView {
    CGFloat orinY = 0;
    for (NSInteger index = 0; index < self.dataList.count; index ++) {
        InputPayItemModel *itemModel = self.dataList[index];
        InputPayItemView *itemView = [[InputPayItemView alloc]initWithFrame:CGRectMake(0, orinY, self.bgView.width, 68)];
        [self.bgView addSubview:itemView];
        itemView.data = itemModel;
        orinY = itemView.bottom;
        if (index == self.dataList.count - 1) {
            itemView.lineView.hidden = YES;
        }
        itemView.tag = index;
        [itemView addTarget:self action:@selector(clickItemControl:) forControlEvents:UIControlEventTouchUpInside];
        
        if (itemModel.isSelect) {
            self.preItemView = itemView;
        }
        
        [self.views addObject:itemView];
    }
    self.bgView.height = orinY;
}
#pragma mark - UITexFieldDelegate
- (void)editingChangedTextField:(UITextField *)textField {
    for (InputPayItemModel *item in self.dataList) {
        item.amount = textField.text.floatValue;
    }
}
#pragma mark - click
- (void)clickItemControl:(InputPayItemView *)sender {
    if (sender == self.preItemView) {
        return;
    }
    self.preItemView.data.isSelect = NO;
    self.preItemView.data = self.preItemView.data;
    self.preItemView = sender;
    self.preItemView.data.isSelect = YES;
    self.preItemView.data = self.preItemView.data;
    
    for (InputPayItemView *item in self.views) {
        if (item.data.hasPeriods) {
            item.data = item.data;
        }
    }
}
- (void)clickPayButton:sender {
    if (self.preItemView.data.amount <= 0) {
        [SVProgressHUD showErrorWithStatus:@"付款金额不能小于0！"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    if (IsStrEmpty(self.dataModel.orderId)) {
        [self createOrder];
    } else {
        WEAKSELF
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"该笔支付是否为尾款支付？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"是" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.dataModel.isLater = YES;
            [weakSelf createOrder];
        }];
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"否" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            weakSelf.dataModel.isLater = NO;
            [weakSelf createOrder];
        }];
        [alert addAction:cancleAction];
        [alert addAction:sureAction];
        [cancleAction setValue:kColor153 forKeyPath:@"_titleTextColor"];
        [sureAction setValue:rgba(254, 118, 15, 1) forKeyPath:@"_titleTextColor"];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
- (void)createOrder {
    [SVProgressHUD showWithStatus:@"下单中..."];
    WK(weakSelf)
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:[Utilities removeNumberZeroWithDouble:self.preItemView.data.amount] forKey:@"amount"];
    [parameters setObject:self.preItemView.data.Id forKey:@"payType"];
    [parameters setObject:self.dataModel.type forKey:@"type"];
    [parameters setObject:@(self.preItemView.data.periods) forKey:@"periods"];
    [parameters setObject:self.dataModel.sellerId forKey:@"sellerId"];
    if (self.dataModel.isJiuDian) {
        [parameters setObject:self.dataModel.payMode forKey:@"payMode"];
    }
    if (IsStrNotEmpty(self.dataModel.orderId)) {
        [parameters setObject:self.dataModel.orderId forKey:@"orderId"];
    }
    [TTHttpManager postRequestWithUrl:[NSString stringWithFormat:@"%@/yunPayCenter/yunGenerateOrder", TT_Global_Api_Domain] TimeOut:10 PostData:parameters FinishBlock:^(id  _Nonnull data) {
        [SVProgressHUD dismiss];
        BaseResponse *responModel = [BaseResponse modelWithJSON:data];
        if (responModel.success) {
            if ([data[@"data"] isKindOfClass:[NSString class]]) {
                [weakSelf sendPayRequestWithResponse:[data[@"data"] mj_JSONObject]];
            } else if ([data[@"data"] isKindOfClass:[NSDictionary class]]) {
                [weakSelf sendPayRequestWithResponse:data[@"data"]];
            }
        } else {
            [SVProgressHUD showWithStatus:responModel.message];
            [SVProgressHUD dismissWithDelay:1];
        }
    } FailedBlock:^(NSError * _Nonnull error) {
        [SVProgressHUD showWithStatus:@"请检查网络~"];
        [SVProgressHUD dismissWithDelay:1];
    }];
}
- (void)sendPayRequestWithResponse:(NSDictionary *)responseDic {
    if (responseDic[@"appPayRequest"] != nil) {
        [UMSPPPayUnifyPayPlugin payWithPayChannel:self.preItemView.data.channel payData:[responseDic[@"appPayRequest"] mj_JSONString] callbackBlock:^(NSString *resultCode, NSString *resultInfo) {
            NSLog(@"%@ %@", resultCode, resultInfo);
            if ([resultCode isEqualToString:@"1003"]) {
                
            }
        }];
    } else if (responseDic[@"resp_data"] != nil) {
        TT_NavigationViewController *navController = (TT_NavigationViewController *)[TT_TabbarViewController shareTabbar].selectedViewController;
        LKLWebViewController *vc = [[LKLWebViewController alloc]init];
        vc.urlString = responseDic[@"resp_data"][@"counter_url"];
        vc.respData = [InputLKLResultModel modelWithDictionary:responseDic].resp_data;
        [navController pushViewController:vc animated:YES];
        [navController removeViewController:self animated:YES];
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    [[UIApplication sharedApplication].delegate.window endEditing:YES];
}
#pragma mark - lazy
- (NSMutableArray<InputPayItemModel *> *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}
- (NSMutableArray<InputPayItemView *> *)views {
    if (!_views) {
        _views = [NSMutableArray array];
    }
    return _views;
}
- (UIView *)bgView {
    if (!_bgView) {
        UIView *view = [[UIView alloc]init];
        view.backgroundColor = UIColor.whiteColor;
        view.frame = CGRectMake(15, 15, kScreenWidth - 30, 68 * 2);
        view.layer.masksToBounds = YES;
        view.layer.cornerRadius = 10;
        _bgView = view;
    }
    return _bgView;
}
- (UIButton *)payButton {
    if (!_payButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:15 weight:UIFontWeightBold];
        button.frame = CGRectMake(15, 0, kScreenWidth - 30, 40);
        button.layer.cornerRadius = 20;
        button.layer.masksToBounds = YES;
        [button setBackgroundImage:[UIImage imageNamed:@"rect_orange"] forState:UIControlStateNormal];
        _payButton = button;
    }
    return _payButton;
}
- (UITextField *)textField {
    if (!_textField) {
        UITextField *tf = [[UITextField alloc]initWithFrame:CGRectMake(20, 30, kScreenWidth - 40, 50)];
        tf.textColor = kColor51;
        NSMutableAttributedString *placeHolder = [[NSMutableAttributedString alloc]initWithString:@"请输入付款金额(单位元)"];
        placeHolder.color = kColor184;
        placeHolder.font = [UIFont systemFontOfSize:28 weight:UIFontWeightBold];
        tf.attributedPlaceholder = placeHolder;
        tf.font = [UIFont systemFontOfSize:30 weight:UIFontWeightBold];
        tf.clearButtonMode = UITextFieldViewModeNever;
        tf.keyboardType = UIKeyboardTypeDecimalPad;//UIKeyboardTypeNumberPad UIKeyboardTypeDecimalPad 小数点
        tf.secureTextEntry = NO;
        tf.tintColor = kGreenColor;
        tf.delegate = self;
        [tf addTarget:self action:@selector(editingChangedTextField:) forControlEvents:UIControlEventEditingChanged];
        tf.textAlignment = NSTextAlignmentCenter;
        _textField = tf;
    }
    return _textField;
}
@end


/**
 L2024120914531379138
 
 */
